# -*- coding:utf-8 -*-
"""
Ficheiro que trata os logs.

Autores: O. Mílitão, R. Josué
Data: 03-05-2012
"""
import plotgraf

LOG_FILE = "ufw.log"
        
def getLogs():
    """
    Metodo que retorna os logs do ficheiro de logs
    """
    fl = open(LOG_FILE, "r")
    logsProcess = []
    for line in fl:
        logsProcess.append(line.split(" "))
    logs = []
    for log in logsProcess:
        date_log = log[0]+log[1]+log[2]
        for x in log:
            if x.startswith("IN="):
                in_log = x.strip("IN=")
            elif x.startswith("OUT="):
                out_log = x.strip("OUT=")
            elif x.startswith("SRC="):
                src_log = x.strip("SRC=")
            elif x.startswith("DST="):
                dst_log = x.strip("DST=")
            elif x.startswith("PROTO="):
                proto_log = x[6:]
            elif x.startswith("SPT="):
                port_log = x[4:]
        
        logs.append([date_log,in_log,out_log,src_log,dst_log,proto_log,port_log])

    return logs
    pass

def getLogsLocation():
    """
    Metodo que adiciona a cada log a sua localização geográfica.
    """
    import pygeoip
    GI = pygeoip.GeoIP("GeoIP.dat", pygeoip.MEMORY_CACHE)
    logs = getLogs()
    logs_final = []
    for log in logs:
        #if 6 < len(log[3]) < 16: #exclui os IPv6
            try:
                info = GI.record_by_addr(log[3])
                logs_final.append([log[0],log[1],log[2],log[3],log[4],log[5],log[6],\
                                        info["continent"],\
                                        info["country_name"],\
                                        info["city"],\
                                        info["longitude"],\
                                        info["latitude"]])
                
            except:
                pass
    return logs_final
    pass

def printLogs():
    """
    Metodo que apresenta na consolas os logs.
    """
    logs=getLogsLocation()
    print "DATE\tIN_LOG\tOUT_LOG\tSRC_IP\tDST_IP\tPROTO\tPORT\tCONTINET\tCOUNTRY\tTOWN"
    for log in logs:
        print log[0]+"\t"+log[1]+"\t"+log[2]+"\t"+log[3]+"\t"+log[4]+"\t"+log[5]+"\t"+log[6]+"\t"+log[7]+"\t"+log[8]+"\t"+log[9]
        

"""
Posições no array
0- data
1- interface entrada
2- interface saida
3- ip origem
4- ip destino
5- protocolo
6- port
7- continent
8- pais
9- cidade
10- longitude
11- altitude
"""
